package com.workplan.client.widgets.userinfo;

import com.general.client.action.ActionHandler;
import com.general.client.basewidget.BaseWidget;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;

public class UserInfo extends BaseWidget implements UserInfoPresenter.Display {

	private static UserInfoUiBinder uiBinder = GWT
			.create(UserInfoUiBinder.class);

	interface UserInfoUiBinder extends UiBinder<Widget, UserInfo> {
	}

	@UiField
	Label mainLabel;
	@UiField
	Label subLabel;
	@UiField
	Anchor link;

	public UserInfo() {
		initWidget(uiBinder.createAndBindUi(this));
		link.setTabIndex(0);
		link.setText("sign out");
	}

	@Override
	public void setUserName(String userName) {
		mainLabel.setText(userName);
	}

	@Override
	public void setCompanyName(String companyName) {
		subLabel.setText(companyName);
	}

	@Override
	public HandlerRegistration addSignOutActionHandler(
			final ActionHandler handler) {
		final HandlerRegistration h1 = link.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				handler.onAction(event);
			}
		});

		final HandlerRegistration h2 = link
				.addKeyDownHandler(new KeyDownHandler() {

					@Override
					public void onKeyDown(KeyDownEvent event) {
						if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
							handler.onAction(event);
						}
					}
				});

		return new HandlerRegistration() {

			@Override
			public void removeHandler() {
				h1.removeHandler();
				h2.removeHandler();
			}
		};
	}

}
